from flask import Blueprint

from controllers import R
from mauth import HasPerm
from models.dept import Dept
from services.dept_service import DeptService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.dept_validator import DeptForm

# 声明一个蓝图
dept = Blueprint("dept", __name__, url_prefix="/sys/dept")

# 声明一个部门业务服务
dept_service = DeptService(model=Dept)


@dept.route("/detail", methods=["POST"])
@HasPerm(access="sys:dept:detail", name="通过id获取部门信息")
def dept_detail():
    """
    通过id获取部门信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = Dept.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = dept_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@dept.route("/page", methods=["POST"])
@HasPerm(access="sys:dept:page", name="分页查询部门列表")
def dept_page():
    """
    分页查询部门列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(dept_service.page(form))


@dept.route("/save", methods=["POST"])
@HasPerm(access="sys:dept:save", name="添加部门")
def dept_save():
    """
    添加部门
    :return:
    """
    form = DeptForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dept_service.save(form)
    return R.success("添加部门成功")


@dept.route("/update", methods=["POST"])
@HasPerm(access="sys:dept:update", name="修改部门")
def dept_update():
    """
    修改部门
    :return:
    """
    form = DeptForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dept_service.update(form)
    return R.success("修改部门成功")


@dept.route("/remove", methods=["POST"])
@HasPerm(access="sys:dept:remove", name="删除部门")
def dept_remove():
    """
    删除部门
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dept_service.remove(form)
    return R.success("删除部门成功")


@dept.route("/list", methods=["POST"])
@HasPerm(access="sys:dept:list", name="查询部门列表")
def dept_list():
    """
    查询部门列表
    :return:
    """
    return R.data(dept_service.list())


@dept.route("/tree", methods=["POST"])
@HasPerm(access="sys:dept:tree", name="查询部门树")
def dept_tree():
    """
    查询部门树
    :return:
    """
    return R.data(dept_service.tree())
